package com.demo0302.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/demo0302/download01.do")
public class Download01Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收文件名参数
        String filename = request.getParameter("filename");
        //2.完成文件下载
        //2.1 设置 Content-Type 响应头
        //根据文件名得到对应的 MIME 类型
        String type = this.getServletContext().getMimeType(filename);
        response.setHeader("Content-Type", type);
        //2.2 设置 Content-Disposition 响应头
        //中文文件乱码问题解决
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        //2.3 设置 文件的输入流 InputStream
        //设置服务器文件存储路径
        String path = "D:\\imgUpload\\" + filename;
        //获取到文件的输入流
        FileInputStream fileInputStream = new FileInputStream(path);
        //获取 response 输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //IO流固定模板
        int length = 0;
        byte[] buffer = new byte[1024];
        while ((length = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer,0,length);
            outputStream.flush();
        }
        //只要关闭输入流即可
        fileInputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
